<template>
  <div class="topic-container">
    <div class="topic-left">
      <!-- 欢迎横幅 -->
      <div class="welcome-banner-wrapper">
        <div class="welcome-banner">
          <div class="banner-content">
            <p class="banner-title">Welcome to Spaces!</p>
            <p class="banner-subtitle">Follow Spaces to explore your interests on Quora.</p>
            <div class="banner-actions">
              <button class="action-button" @click="$router.push('/ask')">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <circle cx="12" cy="12" r="10" />
                  <line x1="12" y1="8" x2="12" y2="16" />
                  <line x1="8" y1="12" x2="16" y2="12" />
                </svg>
                Create a Space
              </button>
              <button class="action-button" @click="handleDiscoverSpaces">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <circle cx="12" cy="12" r="10" />
                  <circle cx="12" cy="12" r="3" />
                </svg>
                Discover Spaces
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="topic-page">
        <!-- 页面头部 -->
        <div class="page-header">
          <div class="header-content">
            <div class="header-left">
              <h1 class="page-title">Discover Spaces</h1>
              <p class="page-subtitle"></p>
            </div>
          </div>
        </div>

        <!-- 热门话题 -->
        <div class="hot-topics-section" v-if="hotTopics.length > 0">
          <div class="section-header">
            <h2 class="section-title">
              <!-- <el-icon>
                <TrendCharts />
              </el-icon> -->
              Spaces you might like
            </h2>
          </div>
          <div class="hot-topics-grid">
            <TopicCard v-for="topic in hotTopics" :key="topic.id" :topic="topic" size="large" :is-hot="true"
              @click="handleTopicClick" @follow-change="handleFollowChange" />
          </div>
        </div>

        <!-- 话题列表 -->
        <div class="topics-section">
          <div class="section-header">
            <h2 class="section-title">
              <!-- <el-icon>
                <CollectionTag />
              </el-icon> -->
              all topics
            </h2>
            <div class="section-actions">
              <!-- 搜索框 -->
              <div class="search-container">
                <el-input v-model="searchKeyword" placeholder="Search topics..." class="search-input" clearable
                  @keyup.enter="handleSearch" @clear="handleClear">
                  <template #prefix>
                    <el-icon>
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
                <el-button type="primary" @click="handleSearch" :loading="loading" class="search-btn">
                  Search
                </el-button>
              </div>

              <!-- 排序选择 -->
              <el-select v-model="sortType" placeholder="排序方式" class="sort-select" @change="handleSortChange">
                <el-option label="hot Sort" :value="3" />
                <el-option label="follower Sort" :value="4" />
                <el-option label="newest Created" :value="2" />
                <el-option label="oldest Created" :value="1" />
              </el-select>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="6" animated />
          </div>

          <!-- 话题网格 -->
          <div v-else-if="topics.length > 0" class="topics-grid">
            <TopicCard v-for="topic in topics" :key="topic.id" :topic="topic" @click="handleTopicClick"
              @follow-change="handleFollowChange" />
          </div>

          <!-- 空状态 -->
          <div v-else class="empty-state">
            <el-empty :image-size="120" description="暂无话题">
              <template #image>
                <el-icon size="120" color="#d3d3d3">
                  <CollectionTag />
                </el-icon>
              </template>
            </el-empty>
          </div>

          <!-- 分页 -->
          <div v-if="total > 0" class="pagination-container">
            <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
              :total="total" :page-sizes="[12, 24, 48]" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>
    <div class="topic-right">
      <div class="pending-invites-card">
        <h3 class="card-title">Pending Invites</h3>
        <div class="empty-state">
          <div class="empty-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
              <path d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
            </svg>
          </div>
          <p class="empty-text">No invites</p>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import TopicCard from '@/components/TopicCard.vue'
import { getHotTopics, getTopicList } from '@/api/topic'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const sortType = ref(3) // 默认热度排序
const topics = ref([])
const hotTopics = ref([])
const total = ref(0)

const pagination = reactive({
  pageNum: 1,
  pageSize: 24
})

// 生命周期
onMounted(() => {
  loadHotTopics()
  loadTopics()
})



// 方法
const loadHotTopics = async () => {
  try {
    const response = await getHotTopics(5)
    if (response.code === 200) {
      hotTopics.value = response.data || []
    }
  } catch (error) {
    console.error('获取热门话题失败:', error)
  }
}

const loadTopics = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      sortType: sortType.value,
      keyword: searchKeyword.value.trim() || undefined
    }

    const response = await getTopicList(params)
    if (response.code === 200) {
      topics.value = response.data.data || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取话题列表失败')
    }
  } catch (error) {
    console.error('获取话题列表失败:', error)
    ElMessage.error('获取话题列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageNum = 1
  loadTopics()
}

const handleClear = () => {
  searchKeyword.value = ''
  pagination.pageNum = 1
  loadTopics()
}

const handleSortChange = () => {
  pagination.pageNum = 1
  loadTopics()
}

const handleTopicClick = (topic) => {
  router.push(`/topic/${topic.id}`)
}

const handleFollowChange = (data) => {
  // 更新热门话题中的关注状态
  const hotTopic = hotTopics.value.find(t => t.id === data.topicId)
  if (hotTopic) {
    hotTopic.isFollowed = data.isFollowed
    if (data.isFollowed) {
      hotTopic.followerCount = (hotTopic.followerCount || 0) + 1
    } else {
      hotTopic.followerCount = Math.max(0, (hotTopic.followerCount || 0) - 1)
    }
  }

  // 更新话题列表中的关注状态
  const topic = topics.value.find(t => t.id === data.topicId)
  if (topic) {
    topic.isFollowed = data.isFollowed
    if (data.isFollowed) {
      topic.followerCount = (topic.followerCount || 0) + 1
    } else {
      topic.followerCount = Math.max(0, (topic.followerCount || 0) - 1)
    }
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  loadTopics()
}

const handleCurrentChange = (page) => {
  pagination.pageNum = page
  loadTopics()
}

const handleDiscoverSpaces = () => {
  // 滚动到话题列表区域
  const topicsSection = document.querySelector('.topics-section')
  if (topicsSection) {
    topicsSection.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}
</script>

<style lang="scss" scoped>
.topic-container {
  max-width: 1400px;
  width: 100%;
  display: flex;
  gap: 24px;
}

.topic-left {
  flex: 1;
  min-width: 0;
}

.topic-right {
  width: 300px;
  flex-shrink: 0;
}

.pending-invites-card {
  background: #ffffff;
  border: 1px solid #dee0e1;
  border-radius: 4px;
  padding: 0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);

  .card-title {
    font-size: 13px;
    font-weight: 500;
    color: #2e3338;
    margin: 0;
    padding: 12px 16px;
    border-bottom: 1px solid #e4e6e8;
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 50px 20px 40px;

    .empty-icon {
      margin-bottom: 8px;
      
      svg {
        color: #d4d5d7;
        stroke: #d4d5d7;
        width: 40px;
        height: 40px;
      }
    }

    .empty-text {
      font-size: 13px;
      color: #939598;
      margin: 0;
      font-weight: 400;
    }
  }
}


.welcome-banner-wrapper {
  margin: 0 0 14px 0;
}

.welcome-banner {
  background: #ffffff;
  border: 1px solid #e4e6e8;
  border-radius: 6px;
  padding: 15px 36px;
  position: relative;
  overflow: hidden;
  // min-height: 160px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);

  &::before {
    content: '';
    position: absolute;
    top: -10px;
    right: 0;
    bottom: -10px;
    width: 50%;
    background: url('/tips_bg.webp') no-repeat center right;
    background-size: contain;
    opacity: 1;
    pointer-events: none;
    z-index: 0;
  }

  .banner-content {
    position: relative;
    z-index: 1;
    max-width: 60%;

    .banner-title {
      font-size: 20px;
      color: #1a1a1a;
      line-height: 1.3;
    }

    .banner-subtitle {
      font-size: 13px;
      color: #636466;
      margin: 0 0 20px 0;
      line-height: 1.5;
    }

    .banner-actions {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;

      .action-button {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        padding: 8px 18px;
        background: #ffffff;
        border: 1.5px solid #2e69ff;
        border-radius: 18px;
        color: #2e69ff;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        line-height: 1.4;

        svg {
          flex-shrink: 0;
          margin-top: 1px;
        }

        &:hover {
          background: #f0f5ff;
          border-color: #1557ff;
          color: #1557ff;
        }

        &:active {
          transform: scale(0.98);
        }
      }
    }
  }
}

.topic-page {
  width: 100%;
  margin: 0 auto;
  padding: 0;
}

.page-header {
  // margin-bottom: 32px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    gap: 24px;
  }

  .header-left {
    flex: 1;

    .page-title {
      font-size: 32px;
      font-weight: 700;
      color: $text-color;
      margin: 0 0 8px 0;
    }

    .page-subtitle {
      font-size: 16px;
      color: $text-secondary;
      margin: 0;
    }
  }


}

.hot-topics-section {
  margin-bottom: 48px;

  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;

    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      // color: $text-color;
      margin: 0;

      .el-icon {
        color: $primary-color;
      }
    }
  }

  .hot-topics-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 20px;
  }
}

.topics-section {
  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;

    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 20px;
      font-weight: 600;
      color: $text-color;
      margin: 0;

      .el-icon {
        color: $primary-color;
      }
    }

    .section-actions {
      display: flex;
      align-items: center;
      gap: 16px;

      .search-container {
        display: flex;
        align-items: center;
        gap: 8px;

        .search-input {
          width: 250px;
        }

        .search-btn {
          white-space: nowrap;
        }
      }

      .sort-select {
        width: 140px;
      }
    }
  }

  .loading-container {
    margin: 20px 0;
  }

  .topics-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 20px;
    margin-bottom: 32px;
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 32px;
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .topic-container {
    flex-direction: column;
    gap: 20px;
  }

  .topic-right {
    width: 100%;
  }

  .welcome-banner-wrapper {
    padding: 0 16px;
    margin-bottom: 20px;
  }

  .welcome-banner {
    padding: 24px 28px;

    .banner-content {
      max-width: 65%;

      .banner-title {
        font-size: 24px;
      }

      .banner-subtitle {
        font-size: 15px;
      }
    }
  }

  .topic-page {
    padding: 16px;
  }

  .page-header {
    .header-content {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
    }

    .header-right {
      .search-input {
        width: 100%;
      }
    }
  }

  .hot-topics-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 16px;
  }

  .topics-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .topic-right {
    display: none;
  }

  .welcome-banner-wrapper {
    padding: 0 12px;
    margin-bottom: 16px;
  }

  .welcome-banner {
    padding: 20px;
    background-position: right bottom;
    min-height: auto;

    &::before {
      width: 50%;
      opacity: 0.6;
    }

    .banner-content {
      max-width: 100%;

      .banner-title {
        font-size: 20px;
        margin-bottom: 8px;
      }

      .banner-subtitle {
        font-size: 14px;
        margin-bottom: 16px;
      }

      .banner-actions {
        flex-direction: column;
        gap: 10px;

        .action-button {
          width: 100%;
          justify-content: center;
          padding: 10px 20px;
          font-size: 14px;
        }
      }
    }
  }

  .topic-page {
    padding: 12px;
  }

  .page-header {
    margin-bottom: 24px;

    .header-left {
      .page-title {
        font-size: 24px;
      }

      .page-subtitle {
        font-size: 14px;
      }
    }
  }

  .hot-topics-section {
    margin-bottom: 32px;
  }

  .hot-topics-grid,
  .topics-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 12px;
  }

  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;

    .section-actions {
      .sort-select {
        width: 100%;
      }
    }
  }
}
</style>
